"""
_*_ : utf-8 _*_ 
@Time: 2023/10/31 22:00
@Author: LWK
@File: 061_ajax_豆瓣电影
@Project: demo01
"""

import urllib.request
import urllib.parse


#
# url = 'https://movie.douban.com/j/chart/top_list?'
#
# headers = {
#     'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
#                   'Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
# }
#
#
# def getPage(pageNum, pageSize):
#     params = {
#         'type': '10',
#         'interval_id': '100:90',
#         'action': '',
#         'start': (pageNum - 1) * pageSize,
#         'limit': pageSize
#     }
#     data = urllib.parse.urlencode(params)
#     req = urllib.request.Request(url + data, None, headers)
#     res = urllib.request.urlopen(req)
#     return res.read().decode('utf-8')
#
#
# # open方法默认情况下使用的是GBK的编码 如果我们想板寸汉字，那么需要再open方法中指定编码格式为utf-8
# # fp = open('../temp/douban.json', 'w', encoding='utf-8')
# # fp.write(content)
# # fp.close()
# with open('../temp/douban.json', 'w', encoding='utf-8') as fp:
#     for i in range(1, 11):
#         fp.write(getPage(i, 20))

def creat_request(page_num, page_size):
    url = 'https://movie.douban.com/j/chart/top_list?'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
    }
    params = {
        'type': '10',
        'interval_id': '100:90',
        'action': '',
        'start': (page_num - 1) * page_size,
        'limit': page_size
    }
    data = urllib.parse.urlencode(params)
    return urllib.request.Request(url + data, None, headers)


def get_content(req):
    res = urllib.request.urlopen(req)
    content = res.read().decode('utf-8')
    return content


def down_load(content, page):
    with open('../temp/douban_%s.json' % str(page), 'w', encoding='utf-8') as fp:
        fp.write(content)


if __name__ == '__main__':
    start_page = int(input('请输入起始的页码：'))
    end_page = int(input('请输入结束的页码：'))

    for page_item in range(start_page, end_page + 1):
        req_init = creat_request(page_item, 20)
        content_init = get_content(req_init)
        down_load(content_init, page_item)
